package com.jiangruan.javaproject.service;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.bean.BitCoinRpc;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:张子寒
 * @email:1594426628@qq.com
 * @desc:该类用于实现调用比特币客户端的getbestblockhash的roc功能
 * @DateTime:2021-12-16
 **/
public class GetBestBlockHashService {
    public BitCoinRpc getBestBlockHash(){
        //准备用户身份信息
        String author=Constants.BITCOIN_PRC_USER+":"+Constants.BITCOIN_RPC_PWO;
        Base64.Encoder encoder=Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());

        //准备请求头信息
        Map<String,String>header=new HashMap<>();
        header.put("ContentType","appLication/json");
        header.put("Authorization","Basic "+authorBase64);

        //rpc请求格式
        Map<String,Object>data=new HashMap<>();
        data.put("id",1001);
        data.put("method","getbestblockhash");
        data.put("params",null);
        data.put("json_rpc","2.0");
        byte[] dataBytes = JSONObject.toJSONBytes(data);
        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL,header,dataBytes);

        BitCoinRpc bitCoinRpc = JSONObject.parseObject(result, BitCoinRpc.class);
        return bitCoinRpc;
    }
}
